## Snakes on a Payload
## Copyright (C) 2011 CORE Security Technologies
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 2
## of the License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
##
## Authors:
## 2011/09/11 - Pedro Varangot (pvarangot@)
## 2011/09/11 - Fernando Russ (fruss@)



import sys

import tempfile
from objcopy import ObjCopy
from elfsource import ReadElfSource
import os
import argparse
import itertools
import json
from archs import Arch


parser = argparse.ArgumentParser(description='describelib - Snakes on a Payload - Copyright (C) 2011 CORE Security Technologies', epilog="relax.")
parser.add_argument('OUT_DIR', help='the path were the .json file(s) will be generated.')
parser.add_argument('-l', dest='INPUT_LIBS', default=list(), action='append', help='add library to inspecto. (eg: -l/lib/x86_64-linux-gnu/libm.so.6)')
parser.add_argument('-a', dest='TARGET_ARCH', default="no-arch!", help='target arch (eg: android-arm, linux-i386)')


args = parser.parse_args()

arch = Arch.byName( args.TARGET_ARCH )

for lib_filename in args.INPUT_LIBS:
    
    out_filename = os.path.join( args.OUT_DIR, os.path.basename(lib_filename) + ".json")    
    print "%s -> %s" % (lib_filename, out_filename)
    elf = ReadElfSource(arch, lib_filename )
    
    symbol_descr = { "export-as": os.path.basename(lib_filename), 
                     "symbols": [symbol_name for symbol_name in elf.symbols.keys() if len(symbol_name) > 0] }    
    with open(out_filename, "w+b") as f:
        f.write( json.dumps(symbol_descr) )


